package net.lesscoding;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import io.netty.bootstrap.Bootstrap;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.buffer.ByteBufAllocator;
import io.netty.channel.*;
import io.netty.channel.nio.AbstractNioChannel;
import io.netty.channel.nio.NioEventLoop;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.logging.LoggingHandler;
import lombok.extern.slf4j.Slf4j;
import net.lesscoding.common.Const;
import net.lesscoding.rpc.codec.ClassCodec;
import org.junit.Test;

import java.nio.channels.SelectionKey;
import java.util.concurrent.CountDownLatch;

/**
 * @author eleven
 * @date 2024/12/3 15:14
 * @apiNote
 */
@Slf4j
public class ServerTest {
    @Test
    public void clientTimeoutTest() {
        //new ServerBootstrap().option() 是给ServerSocketChannel设置参数的
        //new ServerSocketChannel().childOption() 是给SocketChannel设置参数的
        NioEventLoopGroup group = new NioEventLoopGroup();
        try {
            Bootstrap bootstrap = new Bootstrap()
                    .group(group)
                    .channel(NioSocketChannel.class)
                    .option(ChannelOption.CONNECT_TIMEOUT_MILLIS, 100)
                    .handler(new LoggingHandler());
            ChannelFuture future = bootstrap.connect(Const.HOST, Const.PORT);
            future.sync().channel().closeFuture().sync();
        } catch (Exception e) {
            log.error("连接超时", e);
        } finally {
            group.shutdownGracefully();
        }
    }

    @Test
    public void backlogServerTest() throws InterruptedException {
        /**
         * 只有在accept处理不过来的时候，才会放到全连接队列里。
         * 测试的时候需要再 {@link NioEventLoop#processSelectedKey(SelectionKey, AbstractNioChannel)}这个类的 696行打断点
         *
         * if ((readyOps & (SelectionKey.OP_READ | SelectionKey.OP_ACCEPT)) != 0 || readyOps == 0) {
         *     unsafe.read();
         * }
         *
         */

        new ServerBootstrap()
                .group(new NioEventLoopGroup())
                .option(ChannelOption.SO_BACKLOG, 1024)
                .childOption(ChannelOption.TCP_NODELAY, true)
                .channel(NioServerSocketChannel.class)
                .childHandler(new ChannelInitializer<NioSocketChannel>() {
                    @Override
                    protected void initChannel(NioSocketChannel ch) throws Exception {
                        ch.pipeline().addLast(new LoggingHandler());
                    }
                })
                .bind(Const.PORT);
        new CountDownLatch(1).await();
    }

    @Test
    public void byteBufServerTest() throws InterruptedException {
        new ServerBootstrap()
                .group(new NioEventLoopGroup())
                .channel(NioServerSocketChannel.class)
                .childHandler(new ChannelInitializer<NioSocketChannel>() {
                    @Override
                    protected void initChannel(NioSocketChannel ch) throws Exception {
                        ch.pipeline()
                                .addLast(new LoggingHandler())
                                .addLast(new ChannelInboundHandlerAdapter() {
                                    @Override
                                    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
                                        ByteBufAllocator alloc = ctx.alloc();
                                        log.info("alloc buffer: {}", alloc);
                                        super.channelRead(ctx, msg);
                                    }
                                });

                    }
                })
                .bind(Const.PORT);
        new CountDownLatch(1).await();
    }

    @Test
    public void backlogClientTest() throws InterruptedException {
        NioEventLoopGroup group = new NioEventLoopGroup();
        Bootstrap bootstrap = new Bootstrap()
                .group(group)
                .channel(NioSocketChannel.class)
                .handler(new ChannelInitializer<NioSocketChannel>() {
                    @Override
                    protected void initChannel(NioSocketChannel ch) throws Exception {
                        ch.pipeline()
                                .addLast(new LoggingHandler())
                                .addLast(new ChannelInboundHandlerAdapter() {
                                    @Override
                                    public void channelActive(ChannelHandlerContext ctx) throws Exception {
                                        ctx.writeAndFlush(ctx.alloc().buffer().writeBytes("Hello World".getBytes()));
                                        super.channelActive(ctx);
                                    }
                                });
                    }
                });
        ChannelFuture future = bootstrap.connect(Const.HOST, Const.PORT).sync();
        future.channel().closeFuture().sync();
    }

    @Test
    public void gsonTest() {
        Gson gson = new GsonBuilder()
                .registerTypeAdapter(Class.class, new ClassCodec())
                .create();
        System.out.println(gson.toJson(String.class));
    }
}
